import { HttpException, HttpStatus, Inject, Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { PrismaService } from 'src/prisma/prisma.service';
import { Prisma, User } from '@prisma/client';
import { RedisService } from 'src/redis/redis.service';
import { LoginUserDto } from './dto/login-user.dto';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class UserService {
    @Inject(PrismaService)
    private prismaService: PrismaService
    @Inject(RedisService)
    private redisService: RedisService;
    @Inject(JwtService)
    private jwtService: JwtService;

    // 注册
    async create(user: CreateUserDto) {
        /* 
        - 校验 redis 中的验证码 
        - 校验重复用户
        */
        let captcha = await this.redisService.get(`captcha_${user.email}`)
        if (!captcha) {
            throw new HttpException("验证码已经失效", HttpStatus.BAD_REQUEST)
        }
        if (captcha !== user.captcha) {
            throw new HttpException("验证码错误", HttpStatus.BAD_REQUEST)
        }
        const foundUser = await this.prismaService.user.findUnique({
            where: {
                username: user.username
            }
        })
        if (foundUser) {
            throw new HttpException('用户已存在', HttpStatus.BAD_REQUEST);
        }
        return await this.prismaService.user.create({
            data: {
                username: user.username,
                password: user.password,
                nickName: user.nickName,
                email: user.email
            },
            select: {
                id: true,
                username: true,
                nickName: true,
                email: true,
                headPic: true,
                createTime: true
            }
        })
    }

    // 登录
    async login(loginUser: LoginUserDto) {
        const userInfo = await this.prismaService.user.findUnique({
            where: {
                username: loginUser.username
            }
        })
        if (!userInfo) {
            throw new HttpException("未注册用户", HttpStatus.ACCEPTED)
        }
        if (loginUser.password !== userInfo.password) {
            throw new HttpException("密码错误", HttpStatus.ACCEPTED)
        }
        let token = this.jwtService.sign({
            userId: userInfo.id,
            username: userInfo.username
        }, { expiresIn: '7d' })
        return {
            userInfo,
            token
        }
    }


    // 获取好友列表
    async friendship(userId: number , name:string) {
        /* 
        - 查询 `friendship` 表 找到用户的好友关系
        - 将好友关系用 Set 合并去重 并 去除自身 得到所有 好友关系的id
        - 遍历查询好友的 user 信息 返回
        */
        
        const friends = await this.prismaService.friendship.findMany({
            where: { OR: [{ userId }, { friendId: userId }] }
        })
        
        //  [ { userId: 1, friendId: 3 }, { userId: 2, friendId: 3 } ]
        const set = new Set<number>()
        friends.forEach(item => {
            set.add(item.friendId)
            set.add(item.userId)
        })
        const friendRes = [...set].filter(item => item !== userId)

        
        let friendUserRes = []
        for (let item of friendRes) {
            let user = await this.prismaService.user.findUnique({
                where: { id: item },
                select: {
                    id: true,
                    username: true,
                    nickName: true,
                    email: true
                }
            });
            friendUserRes.push(user);
        }
        return friendUserRes.filter((item:User) => item.nickName.includes(name || ''))
    }

    // 根据id 获取详细信息
    async getUserInfoByid(userId:number){
        return await this.prismaService.user.findUnique({
            where:{
                id:userId
            }
        })
    }
}
